package com.telit.android.service.impl;

import com.telit.android.dao.AppHomePageApplicationDao;
import com.telit.android.entity.AppHomePageApplication;
import com.telit.android.service.AppPageApplicationService;
import com.telit.common.util.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zhouyu
 * @description 首页应用实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AppPageApplicationServiceImpl implements AppPageApplicationService {

    @Autowired
    private AppHomePageApplicationDao appHomePageApplicationDao;


    @Override
    public List<AppHomePageApplication> queryByUserId(String userRole) {
        Long userId = JwtTokenUtils.getId();
        List<AppHomePageApplication> list=null;//appHomePageApplicationDao.queryByUserId(userId);
        List<AppHomePageApplication> result = new ArrayList<>();
        if (list==null || list.size()==0){
            if(userRole!=null && !"".equals(userRole)) {
                String[] roles = userRole.split(",");
                Map<String,Object> map = new HashMap<>();
                for (String role : roles) {
                    list = appHomePageApplicationDao.queryDefaultPage(role);
                    list.forEach(page-> map.put(page.getApplicationName(),page));
                }
                List<AppHomePageApplication> finalResult = result;
                map.values().forEach(e->{
                    finalResult.add((AppHomePageApplication) e);
                });
/*                finalResult.forEach(page -> {
                    page.setUserId(Long.valueOf(userId));
                    appHomePageApplicationDao.insertSelective(page);
                });*/
                result = finalResult;
            }
        } else {
            result = list;
        }
        //TODO:v1.1.0 预览图片
//        result.forEach(e->{
//            String url = MinioUtils.previewImg(e.getImageUrl());
//            e.setImageUrl(url);
//        });
        return result;
    }

    @Override
    public void updateAppPage(List<AppHomePageApplication> list) {
        Long userId = JwtTokenUtils.getId();
        appHomePageApplicationDao.deleteByUserId(userId);
        list.forEach(page->{
            page.setUserId(Long.valueOf(userId));
            String imageUrl=appHomePageApplicationDao.queryImageUrl(page.getApplicationName());
            page.setImageUrl(imageUrl);
            appHomePageApplicationDao.insertSelective(page);
        });
    }
}
